<template>
  <div>
    <div class="search-box">
      <el-input v-model="search" placeholder="请输入搜索关键词" />
      <el-button type="primary" @click="searchQuestion()">
        <el-icon> <Search /> </el-icon> 搜索
      </el-button>
    </div>

    <div
      class="tags-container"
      @mouseenter="showTags = true"
      @mouseleave="showTags = false"
    >
      <div class="hot-tag">热门标签</div>
      <transition name="fade">
        <div class="tags" v-if="showTags">
          <div
            @click="changeTag(index)"
            class="tag"
            v-for="(item, index) in Tag"
            :key="item.Id"
            :class="index === activeTag ? 'active' : ''"
          >
            <span>{{ item.TagName }}</span>
            <span>
              <el-icon><Star /></el-icon>{{ item.Count }}
            </span>
          </div>
        </div>
      </transition>
    </div>

    <div class="question-list">
      <transition-group name="fade" tag="div">
        <div v-for="item in searchList" :key="item.Id">
          <el-card
            v-if="item.Status !== 0"
            class="card"
            @click="goQuestionDetail(item)"
            style="cursor: pointer"
          >
            <div class="card-title">{{ item.ProblemName }}</div>
            <div class="card-footer">
              <span class="name">{{ item.UserName }}</span>
              <el-tag type="success" effect="light" round>{{
                item.Tag
              }}</el-tag>
              <span class="money">
                <span v-if="item.Money === 0">无悬赏</span>
                <span v-else>
                  <img
                    src="@/assets/jine.png"
                    alt="金额图标"
                    class="money-icon"
                  />
                  <span class="money-colon"> : </span>
                  <!-- 添加冒号 -->
                  <span class="money-amount">{{ item.Money.toFixed(2) }}</span>
                </span>
              </span>
              <span>{{ item.account + '条回答' }}</span>
              <span class="time">{{
                convertISO8601ToSimplified(item.Time)
              }}</span>
              <div
                class="more"
                @click.stop="report(item.Id, item.UserName, item.ProblemName)"
              >
                举报
              </div>
              <el-button
                v-if="
                  !userCollectionStore.UserCollectionInfo.includes('' + item.Id)
                "
                class="delete-button"
                round
                plain
                type="primary"
                @click.stop="collectProblem(item.Id)"
                >收 藏</el-button
              >
              <el-button
                v-else
                class="delete-button"
                round
                plain
                type="error"
                @click.stop="cancelCollectProblem(item.Id)"
                >取消收藏</el-button
              >
            </div>
          </el-card>
        </div>
      </transition-group>
    </div>

    <el-dialog v-model="showReport" title="举报问题" width="500">
      <el-form :model="reportedQuestion">
        <el-form-item label="问题发布人:">
          <el-input v-model="reportedQuestion.FaBuUserName" disabled />
        </el-form-item>
        <el-form-item label="问题:">
          <el-input v-model="reportedQuestion.ProblemName" disabled />
        </el-form-item>
        <el-form-item label="举报原因:">
          <el-input v-model="reportedQuestion.Reason" />
        </el-form-item>
        <el-button type="primary" @click="reportQuestion()">举 报</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  searchQuestionAPI,
  reportQuestionAPI,
  getTagAPI,
  searchQuestionByTagAPI,
  randomQuestionAPI,
  collectProblemAPI,
  cancelCollectProblemAPI,
  getAnswerCountAPI
} from '@/api/user'
import { useUserCollectionStore, useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useQuestionStore } from '@/stores/modules/questionStore'

const router = useRouter()
const userStore = useUserStore()
const questionStore = useQuestionStore()
const userCollectionStore = useUserCollectionStore()

const search = ref('')
const searchList = ref([])
const activeTag = ref(-1)
const Tag = ref([])
const showReport = ref(false)
const reportedQuestion = ref()
const showTags = ref(false)

const getAnswerCount = async (ProblemId) => {
  const res = await getAnswerCountAPI({ ProblemId })
  console.log(res.data)
  let a = String(res.data)
  return a
}

const cancelCollectProblem = async (ProblemId) => {
  const res = await cancelCollectProblemAPI({
    UserName: userStore.userInfo.userName,
    ProblemId
  })
  if (res.data === 1) {
    var newCollection = userCollectionStore.UserCollectionInfo.filter(
      (item) => item !== '' + ProblemId
    )
    userCollectionStore.setUserCollectionInfo(newCollection)
    ElMessage({ message: '取消收藏成功', type: 'success' })
  } else {
    ElMessage.error('取消收藏失败')
  }
}

const collectProblem = async (ProblemId) => {
  const res = await collectProblemAPI({
    UserName: userStore.userInfo.userName,
    ProblemId
  })
  if (res.data === 1) {
    userCollectionStore.UserCollectionInfo.push('' + ProblemId)
    ElMessage({ message: '收藏成功', type: 'success' })
  } else {
    ElMessage.error('收藏失败')
  }
}

// 搜索问题
const searchQuestion = async () => {
  activeTag.value = -1
  const res = await searchQuestionAPI({ ProblemName: search.value })
  searchList.value = res.data
}

// 获取随机问题
const getRandomQuestion = async () => {
  const res = await randomQuestionAPI()
  searchList.value = res.data
  for (const item of searchList.value) {
    item.account = await getAnswerCount(item.Id)
  }
}

// 时间格式化
const convertISO8601ToSimplified = (isoString) => {
  const date = new Date(isoString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 举报问题
const report = (ProblemId, FaBuUserName, ProblemName) => {
  reportedQuestion.value = {
    JuBaoUserName: userStore.userInfo.userName,
    FaBuUserName: FaBuUserName,
    ProblemId: ProblemId,
    Reason: '',
    ProblemName: ProblemName
  }
  showReport.value = true
}

// 提交举报
const reportQuestion = async () => {
  if (
    reportedQuestion.value.JuBaoUserName === reportedQuestion.value.FaBuUserName
  ) {
    ElMessage.error('举报失败，不能举报自己的问题')
    return
  }
  const res = await reportQuestionAPI(reportedQuestion.value)
  if (res.data === 1) {
    ElMessage.success('举报成功')
    showReport.value = false
  } else {
    ElMessage.error('举报失败')
  }
}

// 跳转到问题详情
const goQuestionDetail = (Question) => {
  questionStore.removeQuestionInfo()
  questionStore.setQuestionInfo(Question)
  router.push({ path: '/home/user/QuestionDetail' })
}

// 获取标签
const getTag = async () => {
  const res = await getTagAPI()
  Tag.value = res.data
}

// 切换标签
const changeTag = (index) => {
  activeTag.value = index
  searchQuestionByTag()
}

// 根据标签搜索问题
const searchQuestionByTag = async () => {
  const res = await searchQuestionByTagAPI({
    Tag: Tag.value[activeTag.value].TagName
  })
  searchList.value = res.data
  for (const item of searchList.value) {
    item.account = await getAnswerCount(item.Id)
  }
}

// 初始化
onMounted(() => {
  getTag()
  getRandomQuestion()
})
</script>

<style scoped>
.search-box {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px;
}

.tags-container {
  position: relative;
  display: flex;
  flex-direction: column;
}

.hot-tag {
  padding: 10px;
  cursor: pointer;
  background-color: #3670ee;
  color: white;
  border-radius: 5px;
  text-align: center;
  transition:
    background-color 0.3s,
    transform 0.3s;
}

.hot-tag:hover {
  background-color: #285bb5;
  transform: scale(1.05);
}

.tags {
  display: flex;
  flex-direction: row;
  margin-top: 10px;
  flex-wrap: wrap;
  transition: all 0.3s ease;
}

.tag {
  padding: 10px 15px;
  margin-right: 10px;
  cursor: pointer;
  transition:
    background-color 0.3s,
    transform 0.3s;
}

.tag:hover {
  background-color: #f5f5f5;
  transform: translateY(-2px);
}

.active {
  color: #3670ee;
  background-color: #e7f1ff;
}

.card {
  margin: 10px 0;
  border-radius: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.card:hover {
  transform: translateY(-5px);
}

.card-title {
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 10px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.name {
  font-size: 14px;
  color: #666;
}

.money {
  font-weight: 600;
  color: #f56c6c;
}

.more {
  background-color: #f9f9f9;
  width: 60px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.more:hover {
  background-color: #e0e0e0;
}

.time {
  font-size: 12px;
  color: #999;
}

.question-list {
  margin-left: 25px; /* 设置为25px */
}

/* 添加动画 */
.fade-enter-active,
.fade-leave-active {
  transition:
    opacity 0.5s,
    transform 0.5s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
  transform: translateY(10px); /* 向下移动 */
}
.money {
  font-weight: 600;
  color: #f56c6c;
}

.money-content {
  display: flex; /* 使用 flexbox 使图标和数字对齐 */
  align-items: center; /* 垂直居中对齐 */
}

.money-amount {
  font-size: 16px; /* 设置数字的字体大小 */
  line-height: 20px; /* 设置数字的行高，与图标的高度相同 */
}
</style>
